package com.dinghui.ebookbag.utils;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.dinghui.ebookbag.config.Constants;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//网络请求封装
public class HttpUtils {
    private final long TIMEOUT = 30; //超时时间

    private static Handler handler;

    //无参构造必须写
    private HttpUtils() {
        initHttpUtils();
    }

    //静态内部类单例
    private static class httpUTILS {
        private static HttpUtils instance = new HttpUtils();
    }

    public static HttpUtils getInstance() {
        return httpUTILS.instance;
    }


    //    初始化
    private void initHttpUtils() {
//        创建一个handler,用于从子线程把结果返回给主线程
        handler = new Handler(Looper.getMainLooper());
    }


    /**
     * requesBody传参方式 post请求
     *
     * @param url        接口路径
     * @param bodyParams 参数
     * @param callback   回调
     */
    public void OkHttp3PostWithRequestBody(String url, Map<String, Object> bodyParams, final NetworkCallback callback) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        JSONObject js = new JSONObject();
        try {
            for (Map.Entry<String, Object> param : bodyParams.entrySet()) {
                js.put(param.getKey(), param.getValue());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(TIMEOUT, TimeUnit.SECONDS).readTimeout(TIMEOUT, TimeUnit.SECONDS).build();
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(js));
        Request request = new Request.Builder()
                .addHeader("Authorization", "132456")
                .url(Constants.API.BASE_URL + url)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("onFailure", "onFailure: 请求失败" + e.getMessage());
                //这里可以封装请求返回的一个实例
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            callback.onFail("error");
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //回调的方法执行在子线程。
                if (response.isSuccessful()) {
                    //记住！一定是.string 不然你家就炸了（只能调一次）
                    String string = response.body().string();
                    try {
                        final JSONObject result = new JSONObject(string);
                        String status = result.getString("status");
                        final String message = result.getString("msg");
                        if (status.equals("200") || status.equals("OK")) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (callback != null) {
                                        callback.onSuccess(result);
                                    }
                                }
                            });
                        } else {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (callback != null) {
                                        callback.onFail(message);
                                    }
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.onFail("网络连接失败");
                            }
                        }
                    });
                }

            }
        });

    }

    /**
     * requesBody传参方式 post请求
     *
     * @param url      接口路径
     * @param callback 回调
     */
    public void OkHttp3Get(String url, final NetworkCallback callback) {
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(TIMEOUT, TimeUnit.SECONDS).readTimeout(TIMEOUT, TimeUnit.SECONDS).build();
        Request request = new Request.Builder()
                .addHeader("Authorization", "132456")
                .url(Constants.API.BASE_URL + url)
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("onFailure", "onFailure: 请求失败" + e.getMessage());
                //这里可以封装请求返回的一个实例
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            callback.onFail("error");
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //回调的方法执行在子线程。
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    try {
                        final JSONObject result = new JSONObject(string);
                        String status = result.getString("status");
                        final String message = result.getString("msg");
                        if (status.equals("200") || status.equals("OK")) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (callback != null) {
                                        callback.onSuccess(result);
                                    }
                                }
                            });
                        } else {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (callback != null) {
                                        callback.onFail(message);
                                    }
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.onFail("网络连接失败");
                            }
                        }
                    });
                }

            }
        });

    }


    /**
     * 获取视频指定帧数的图片
     *
     * @param url      视频地址
     * @param timeUs   多少帧数的图片   微秒
     * @param callback
     */
    public void getVideoCover(String url, long timeUs, final BitmapCallBack callback) {

        final MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(url, new HashMap());
        //获得多少帧图片 这里的第一个参数 以微秒为单位
        final Bitmap b = retriever.getFrameAtTime(timeUs, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onBack(b);
//                    retriever.release();
                }
            }
        });

    }


}
